package com.zx._03_并发.chapter_06_compent;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步组件CyclicBarrier
 */
@Slf4j
public class Demo_03_CyclicBarrier {

    public static void main(String[] args) throws InterruptedException {
        int ThreadToatl = 70;//线程数
        int parties = 7;//等待的线程数

        final CyclicBarrier cyclicBarrier = new CyclicBarrier(parties, () -> {
            log.info("龙珠已经集齐！！！！！");
        });

        ExecutorService pool = Executors.newCachedThreadPool();

        for (int i = 0; i < ThreadToatl; i++) {
            final int in = i % 7 + 1;
            Thread.sleep(100L);//执行方法
            pool.execute(() -> {
                try {
                    log.info("获得龙珠 {}", in);
                    cyclicBarrier.await();//执行完成后，开始等待其他线程，等数量等于parties的时候，在往下执行
                    log.info("释放龙珠  {}", in);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        pool.shutdown();
    }
}
